<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管系统</title>
    <link rel="stylesheet" href="./statics/css/index.css">
</head>

<body>
    <div class="nav">
        <input type="button" value="新增图书" onclick="add()" />
    </div>

    <table>
        <tr>
            <th>编号</th>
            <th>书籍名称</th>
            <th>作者名称</th>
            <th>价格</th>
            <th>操作</th>
        </tr>

        <tbody id="bookList">

        </tbody>
    </table>

    <script>
        function add() {
            location.href = './add.html';
        }

        // 后端api路径
        const apiPath = "http://localhost:8000/books";

        // 获取 图书列表标签
        const bookList = document.querySelector("#bookList");

        // 加载完成后就渲染图书信息
        fetch(apiPath, { method: "get" }).then(res => {
            if (res.status = 200) {
                return res.json();
            }
        }).then(data => {
            const content = data.data.map(book => {
                return `
                <tr>
                <td>${book.id}</td>
                <td>${book.bookName}</td>
                <td>${book.bookPrice}</td>
                <td>${book.author}</td>
                <td>
                    <input type="button" value="修改" data-id="${book.id}">
                    <input type="button" value="删除" data-id="${book.id}">
                </td>
                </tr>
                `
            }).join("");

            bookList.innerHTML = content;
        }).catch(err => console.log(err));

        bookList.addEventListener("click", (e) => {
            if (e.target.tagName === "INPUT") {
                if (e.target.value === "修改") {
                    location.href = "./update.html?id=" + e.target.dataset.id;
                }
                if (e.target.value === "删除" && confirm("确认删除")) {
                    // 删除请求
                    fetch(`${apiPath}/${e.target.dataset.id}`, { method: "delete" }).then(res => {
                        if (res.status = 200) {
                            return res.json();
                        }
                    }).then(data => {
                        if (data.code === 200) {
                            location.href = "./index.html";
                        } else {
                            console.log(data.msg);
                        }

                    }).catch(err => console.log(err));
                }
            }
        })
    </script>
</body>

</html>